package br.mcaslib.swiz.controller
{
	import flash.events.IEventDispatcher;
	
	import mx.controls.Alert;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	
	import org.swizframework.utils.services.ServiceHelper;
	
	public class BaseController
	{
		//--------------------------------------------------------------------------
		//
		//  Constructor
		//
		//--------------------------------------------------------------------------
		
		public function BaseController() {
		}
		
		//--------------------------------------------------------------------------
		//
		//  Properties
		//
		//--------------------------------------------------------------------------
		
		[Inject]
		public var serviceHelper:ServiceHelper;
		
		[Dispatcher]
		public var dispatcher:IEventDispatcher;

		//--------------------------------------------------------------------------
		//
		//  Methods
		//
		//--------------------------------------------------------------------------

		public function executeServiceCall( call:AsyncToken, resultHandler:Function, resultHandlerArgs:Array = null ):AsyncToken {
			trace( "Service Call: " + call.message.toString() );
			return serviceHelper.executeServiceCall( call, resultHandler, this.faultHandler, resultHandlerArgs );
		}

		//--------------------------------------------------------------------------
		//
		//  Protected Methods
		//
		//--------------------------------------------------------------------------

		protected function faultHandler( event:FaultEvent ):void {
			var msgError:String
			var msgTitle:String = "Falha no servidor";
			if( event.fault.rootCause ) {
				if( event.fault.rootCause.hasOwnProperty( "msg" ) ) {
					msgError = event.fault.rootCause.msg;
					if ( event.fault.rootCause.hasOwnProperty( "submsg" ) ) {
						if( event.fault.rootCause.submsg ) {
							msgError += "\n\n" + event.fault.rootCause.submsg;
						}
					}
					if ( event.fault.rootCause.hasOwnProperty( "title" ) ) {
						if( event.fault.rootCause.title ) {
							msgTitle = event.fault.rootCause.title;
						}
					}
				} else {
					msgError = event.fault.rootCause.faultDetail + "\n" + event.fault.faultCode;
				}
			} else {
				msgError = event.fault.faultDetail;
			}
			trace( msgError )
			Alert.show( msgError, msgTitle );
		}
	}
}
